package com.aimuceliang.aimuceliang.net;


import com.aimuceliang.aimuceliang.api.ApiException;
import com.aimuceliang.aimuceliang.utils.NetUtils;
import com.aimuceliang.aimuceliang.utils.T;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeoutException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * hepeng Created on 2016/9/30.
 * 类名称： 网络请求订阅者
 */
public abstract class HttpSubscriber<R> extends Subscriber<R> {


    @Override
    public void onStart() {
        super.onStart();
        if (!NetUtils.isConnected()) {
            if (!isUnsubscribed()) {
                unsubscribe();
            }
            T.showShort("请检查网络连接后重试!");
            onFinished();
        }
    }


    @Override
    public void onError(Throwable e) {
        onFinished();
        if (e instanceof HttpException || e instanceof ConnectException || e instanceof SocketTimeoutException || e instanceof TimeoutException) {
            onNetworkException(e);
        } else if (e instanceof ApiException) {
            onApiException(e);
        } else {
            onUnknownException(e);
        }
    }

    @Override
    public void onCompleted() {
        onFinished();
    }


    public abstract void onFinished();

    private void onNetworkException(Throwable e) {
        e.printStackTrace();
        T.showShort("获取数据失败，请检查网络状态");
    }

    private void onApiException(Throwable e) {
        e.printStackTrace();
        T.showShort(e.getMessage());
    }

    private void onUnknownException(Throwable e) {
        e.printStackTrace();
    }


}
